import logging
logging.disable(logging.CRITICAL)
import ctypes,sys,os,json,subprocess,shutil
from PyQt5.QtWidgets import QApplication, QProgressBar,QWidget,QMessageBox,QDialog,QFileDialog,QFormLayout, QVBoxLayout, QHBoxLayout, QPushButton, QCheckBox, QLabel, QLineEdit, QComboBox, QTextEdit
from PyQt5.QtCore import Qt,QTimer
from PyQt5.QtGui import QIcon, QPixmap
from datetime import datetime
import images
from FIF.FIF_Thread import ProgramThread
from FIF.cert_rc import cert,cert_mitmproxy
from util.proxy import set_system_proxy
import webbrowser
     
class ProgramGUI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.work_thread = None
    
    def is_admin(self):
            try:
                return ctypes.windll.shell32.IsUserAnAdmin()
            except:
                return False
    def initUI(self):
        # 创建主布局
        main_layout = QVBoxLayout()
        self.icon = QIcon(":/pic/FIF.ico")
        self.setWindowIcon(self.icon)
        # 窗口设置
        
        
        
        if self.is_admin():
            window_title = "FIF刷题（管理员模式）"
        else:
            window_title = "FIF刷题（非管理员模式）"
        self.setWindowTitle(window_title)
        self.setMinimumSize(600, 1000)
        self.setMaximumSize(600, 1000)
        self.center()

        # 自动登录设置
        pixmap = QPixmap(":/pic/tool.png")
        icon_tool = QIcon(pixmap)
        self.top_layout = QHBoxLayout()
        self.auto_login_checkbox = QCheckBox("自动登录", self)
        self.auto_login_checkbox.setChecked(False)
        self.auto_login_checkbox.toggled.connect(self.toggleAutoLogin)
        self.tool_button = QPushButton(icon_tool, "", self)
        self.tool_button.clicked.connect(self.ShowTool)
        self.top_layout.addWidget(self.auto_login_checkbox)
        self.top_layout.addStretch()
        self.top_layout.addWidget(self.tool_button)

        # 用户名和密码输入框（默认隐藏）
        self.username_label = QLabel("用户名：", self)
        self.username_input = QLineEdit(self)
        self.password_label = QLabel("密码：", self)
        self.password_input = QLineEdit(self)
        self.password_input.setEchoMode(QLineEdit.Password)

        self.username_label.hide()
        self.username_input.hide()
        self.password_label.hide()
        self.password_input.hide()

        # 勾选框和下拉框
        pixmap = QPixmap(":/pic/1.png")
        icon = QIcon(pixmap)
        self.T3_layout = QHBoxLayout()
        self.T3_checkbox = QCheckBox("秒杀模式", self)
        self.T3_checkbox.stateChanged.connect(self.ShowT3Info)
        self.T3_HELP = QPushButton(icon,"", self)
        self.T3_HELP.clicked.connect(lambda:self.ShowHelp("不听音频，直接选答案，建议不要使用。"))
        self.T3_layout.addWidget(self.T3_checkbox)
        self.T3_layout.addStretch()
        self.T3_layout.addWidget(self.T3_HELP)

        self.H_layout = QHBoxLayout()
        self.H_checkbox = QCheckBox("切换窗口", self)
        self.H_checkbox.setChecked(True)  # 默认选中
        self.H_HELP = QPushButton(icon,"", self)
        self.H_HELP.clicked.connect(lambda:self.ShowHelp("切换窗口，便于后续调试，勾上就行。"))
        self.H_layout.addWidget(self.H_checkbox)
        self.H_layout.addStretch()
        self.H_layout.addWidget(self.H_HELP)

        self.IS_TALK_layout = QHBoxLayout()
        self.IS_TALK_checkbox = QCheckBox("完成口语", self)
        self.FastRead_checkbox = QCheckBox("修改数据", self)
        self.IS_TTS_checkbox = QCheckBox("使用TTS", self)
        self.IS_TTS_checkbox.setChecked(False)
        self.FastRead_checkbox.setChecked(False)
        self.TTS_rf_file_path = None # 初始化为None
        self.TTS_path_filed_button = QPushButton("选择参考音频", self)  
        self.checkfilename = QLabel("未选择",self)
        self.checkfilename.setStyleSheet("color:red")
        self.checkfilename.hide()
        self.TTS_rf_text_label = QLabel("参考音频的文本：", self)
        self.TTS_rf_text_line = QLineEdit(self)

        self.IS_TALK_checkbox.stateChanged.connect(self.ShowTalkInfo)
        self.IS_TALK_checkbox.stateChanged.connect(self.showTTS)
        self.IS_TTS_checkbox.stateChanged.connect(self.showTTSconfig)
        self.FastRead_checkbox.stateChanged.connect(self.ShowFastReadInfo)
        self.TTS_path_filed_button.clicked.connect(self.openTTSFileDialog)

        self.IS_TTS_checkbox.hide()
        self.FastRead_checkbox.hide()
        self.TTS_path_filed_button.hide()
        self.TTS_rf_text_line.hide()
        self.TTS_rf_text_label.hide()

        self.IS_TALK_HELP = QPushButton(icon,"", self)
        self.IS_TALK_HELP.clicked.connect(lambda:self.ShowHelp("1、勾选后，将完成口语部分，注意要配置好ADB连接。\n2、修改数据将直接修改数据，不用连接ADB。\n————TTS还未适配不用看下面的————\n3、TTS功能必须下载F5-TTS\n4、并且以次此为文件名存放在当前目录下\n5、推荐显存8G及以上的使用\n6、6-8G显存也能跑，稍慢点\n7、参考音频10s左右，不要超过15s\n8、参考文本要与参考音频内容一致。"))
        self.IS_TALK_layout.addWidget(self.IS_TALK_checkbox)
        self.IS_TALK_layout.addWidget(self.FastRead_checkbox)
        self.IS_TALK_layout.addWidget(self.IS_TTS_checkbox)
        self.IS_TALK_layout.addWidget(self.TTS_path_filed_button)
        self.IS_TALK_layout.addWidget(self.checkfilename)
        self.IS_TALK_layout.addStretch()
        self.IS_TALK_layout.addWidget(self.IS_TALK_HELP)

        self.log_layout = QHBoxLayout()
        self.log = QCheckBox("日志记录：",self)
        self.log.setChecked(True)  # 默认选中
        self.log_help = QPushButton(icon,"", self)
        self.log_help.clicked.connect(lambda:self.ShowHelp("勾选后，将记录日志，便于后续调试。\n运行日志保存在config文件夹下。"))
        self.log_layout.addWidget(self.log)
        self.log_layout.addStretch()
        self.log_layout.addWidget(self.log_help)

        self.LOW_SCORE_layout = QHBoxLayout()
        self.LOW_SCORE_combo = QComboBox(self)
        self.LOW_SCORE_combo.addItems(['60', '70', '80', '90'])
        self.LOW_SCORE_combo.setCurrentText('60')
        self.LOW_SCORE_HELP = QPushButton(icon,"", self)
        self.LOW_SCORE_HELP.clicked.connect(lambda :self.ShowHelp("答题的最低分数，低于此分数将重新答题，建议值60-80\n无限循环可以看看是不是最低值设置的有问题。"))
        self.LOW_SCORE_layout.addWidget(self.LOW_SCORE_combo)
        self.LOW_SCORE_layout.addStretch()
        self.LOW_SCORE_layout.addWidget(self.LOW_SCORE_HELP)

        self.WRONG_ANSWER_layout = QHBoxLayout()
        self.WRONG_ANSWER_combo = QComboBox(self)
        self.WRONG_ANSWER_combo.addItems([str(i) for i in range(0, 4)])
        self.WRONG_ANSWER_combo.setCurrentText('1')
        self.WRONG_ANSWER_HELP = QPushButton(icon,"", self)
        self.WRONG_ANSWER_HELP.clicked.connect(lambda:self.ShowHelp("错误答案的个数，建议值1-3"))
        self.WRONG_ANSWER_layout.addWidget(self.WRONG_ANSWER_combo)
        self.WRONG_ANSWER_layout.addStretch()
        self.WRONG_ANSWER_layout.addWidget(self.WRONG_ANSWER_HELP)

        self.implicitly_wait_time_layout = QHBoxLayout()
        self.implicitly_wait_time_combo = QComboBox(self)
        self.implicitly_wait_time_combo.addItems(['5', '10', '15', '20','30','40'])
        self.implicitly_wait_time_combo.setCurrentText('15')
        self.implicitly_wait_time_HELP = QPushButton(icon,"", self)
        self.implicitly_wait_time_HELP.clicked.connect(lambda:self.ShowHelp("隐式等待时间（implicitly），建议值10-30"))
        self.implicitly_wait_time_layout.addWidget(self.implicitly_wait_time_combo)
        self.implicitly_wait_time_layout.addStretch()
        self.implicitly_wait_time_layout.addWidget(self.implicitly_wait_time_HELP)

        self.Unit_or_Level_layout = QHBoxLayout()
        self.Unit_or_Level = QComboBox(self)
        self.Unit_or_Level.addItems(['Unit', 'Level'])
        self.Unit_or_Level.setCurrentText('Level')
        self.Unit_or_Level_HELP = QPushButton(icon,"", self)
        self.Unit_or_Level_HELP.clicked.connect(lambda:self.ShowHelp("选择答题模式：\nUnit为单元测试（多作业选这个）\nLevel为等级测试（少作业选这个）。"))
        self.Unit_or_Level_layout.addWidget(self.Unit_or_Level)
        self.Unit_or_Level_layout.addStretch()
        self.Unit_or_Level_layout.addWidget(self.Unit_or_Level_HELP)
        # 按钮
        self.start_button = QPushButton("开始", self)
        self.stop_button = QPushButton("停止", self)
        self.stop_button.setEnabled(False)
        self.continue_button = QPushButton("继续", self)
        self.continue_button.hide()

        # 控制台
        self.console_output = QTextEdit(self)
        self.console_output.setFixedHeight(300)
        self.console_output.setReadOnly(True)

        # 错误信息和进度条
        self.underlayout = QHBoxLayout()
        self.error_output = QLabel("错误信息：", self)
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setRange(0, 100)
        self.progress_bar.hide()
        self.progress_bar.setValue(0)
        self.underlayout.addWidget(self.error_output)
        self.underlayout.addStretch()
        self.underlayout.addWidget(self.progress_bar)

        # 布局
        control_layout = QFormLayout()
        control_layout.addRow(self.top_layout)
        control_layout.addRow(self.username_label, self.username_input)
        control_layout.addRow(self.password_label, self.password_input)
        control_layout.addRow(self.T3_layout)
        control_layout.addRow(self.H_layout)
        control_layout.addRow(self.IS_TALK_layout)
        control_layout.addRow(self.TTS_rf_text_label, self.TTS_rf_text_line)
        control_layout.addRow(self.log_layout)
        control_layout.addRow("最低分数：", self.LOW_SCORE_layout)
        control_layout.addRow("错误答案：", self.WRONG_ANSWER_layout)
        control_layout.addRow("隐式等待时间：", self.implicitly_wait_time_layout)
        control_layout.addRow("模式：", self.Unit_or_Level_layout)
        control_layout.addRow(self.start_button)
        control_layout.addRow(self.stop_button)
        control_layout.addRow(self.continue_button)

        self.console_out_layout = QHBoxLayout()
        self.console_out_info = QLabel("控制台输出：", self)
        self.thread_running_animation_label = QLabel('',self)
        self.thread_running_animation_label.hide()
        self.console_out_layout.addWidget(self.console_out_info)
        self.console_out_layout.addStretch()
        self.console_out_layout.addWidget(self.thread_running_animation_label)
        main_layout.addLayout(control_layout)
        main_layout.addLayout(self.console_out_layout)
        main_layout.addWidget(self.console_output)
        main_layout.addLayout(self.underlayout)

        self.setLayout(main_layout)

        # 绑定事件
        self.start_button.clicked.connect(self.onStart)
        self.stop_button.clicked.connect(self.onStop)
        self.continue_button.clicked.connect(self.onContinue)

        # 加载配置
        self.loadConfig()
    def ShowFastReadInfo(self):
        if self.FastRead_checkbox.isChecked():
            self.IS_TTS_checkbox.setChecked(False)
        else:
            pass
    def update_progress(self, value):
        self.progress_bar.setValue(value)
        self.progress_bar.show()
        if value >= 100:
            self.progress_bar.setValue(0)
            self.progress_bar.hide()
    def showTTSconfig(self):
        if self.IS_TTS_checkbox.isChecked():
            self.FastRead_checkbox.setChecked(False)
            self.TTS_path_filed_button.show()
            self.TTS_rf_text_label.show()
            self.TTS_rf_text_line.show()
            self.checkfilename.show()
        else:
            self.TTS_path_filed_button.hide()
            self.TTS_rf_text_label.hide()
            self.TTS_rf_text_line.hide()
            self.checkfilename.hide()
    def showTTS(self):
        if self.IS_TALK_checkbox.isChecked():
            self.FastRead_checkbox.show()
            self.IS_TTS_checkbox.show()
            if self.IS_TTS_checkbox.isChecked():
                self.FastRead_checkbox.setChecked(False)
                self.TTS_path_filed_button.show()
                self.TTS_rf_text_label.show()
                self.TTS_rf_text_line.show()
                self.checkfilename.show()
            else:
                self.TTS_path_filed_button.hide()
                self.TTS_rf_text_label.hide()
                self.TTS_rf_text_line.hide()
                self.checkfilename.hide()
        else:
            self.FastRead_checkbox.hide()
            self.IS_TTS_checkbox.hide()
            self.TTS_path_filed_button.hide()
            self.TTS_rf_text_label.hide()
            self.TTS_rf_text_line.hide()
            self.checkfilename.hide()
    def ShowTool(self):
        
        self.tool_dialog = QDialog(self)
        self.tool_dialog.resize(300,200)
        self.tool_dialog.setWindowTitle("工具")
        self.tool_dialog.setWindowIcon(self.icon)
        self.tool_dialog.setWindowFlags(self.tool_dialog.windowFlags() & ~Qt.WindowContextHelpButtonHint)
        
        self.tool_layout = QFormLayout()
        self.cert_path_filed = None # 初始化为None
        self.cert_path_filed_button = QPushButton("安装证书文件", self)
        self.cert_path_filed_button.clicked.connect(self.InstallFileDialog)
        self.setsystemproxy_button = QPushButton("恢复系统代理", self)
        self.setsystemproxy_button.clicked.connect(lambda: set_system_proxy(enable=False))
        self.setsystemproxy_button.clicked.connect(lambda: QMessageBox.information(self, "提示", "代理已恢复"))
        self.clean_config_button = QPushButton("清空并还原配置", self.tool_dialog)
        self.clean_config_button.clicked.connect(lambda:self.clean_config())
        self.clean_log_button = QPushButton("清空日志", self.tool_dialog)
        self.clean_log_button.clicked.connect(lambda:self.clean_log())
        self.save_config_button = QPushButton("保存配置", self.tool_dialog)
        self.save_config_button.clicked.connect(lambda:self.saveConfig())
        self.feedback_button = QPushButton("反馈", self.tool_dialog)
        self.feedback_button.clicked.connect(lambda:self.openBrowser("https://message.bilibili.com/?spm_id_from=333.999.0.0#/whisper/mid1381831777"))
        self.newVersion_button = QPushButton("下载最新版", self.tool_dialog)
        self.newVersion_button.clicked.connect(lambda:self.openBrowser("https://gitcode.com/lannzy/FIF/releases"))
        self.tool_layout.addRow(self.cert_path_filed_button)
        self.tool_layout.addRow(self.setsystemproxy_button)
        self.tool_layout.addRow(self.save_config_button)
        self.tool_layout.addRow(self.clean_log_button)
        self.tool_layout.addRow(self.clean_config_button)
        self.tool_layout.addRow(self.feedback_button)
        self.tool_layout.addRow(self.newVersion_button)
        
        self.tool_dialog.setLayout(self.tool_layout)
        self.tool_dialog.show()

    def openBrowser(self,url):
        webbrowser.open(url)
    def clean_log(self):
         try:
            for file in os.listdir('./config'):
                if file.endswith('.txt'):
                    os.remove(os.path.join('./config', file))
            QMessageBox.information(self, "提示", "日志已清空！")
         except Exception as e:
            QMessageBox.warning(self, "警告", f"出错啦！\n{e}")
    def clean_config(self):
        try:
            try:
                os.remove("./config/config.json")
            except:
                QMessageBox.warning(self, "警告", "没有找到配置文件！\n尝试还原默认配置中...")
            self.auto_login_checkbox.setChecked(False)
            self.IS_TALK_checkbox.setChecked(False)
            self.T3_checkbox.setChecked(False)
            self.log.setChecked(True)
            self.username_input.clear()
            self.password_input.clear()
            self.LOW_SCORE_combo.setCurrentText("60")
            self.WRONG_ANSWER_combo.setCurrentText("1")
            self.implicitly_wait_time_combo.setCurrentText("10")
            self.cert_path_filed = None
            self.Unit_or_Level.setCurrentText("Level")
            QMessageBox.information(self, "提示", "配置已清空！")
        except Exception as e:
            QMessageBox.warning(self, "警告", f"出错啦！\n{e}")
    def center(self):
        qr = self.frameGeometry()
        screen = QApplication.primaryScreen()
        cp = screen.availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    def openTTSFileDialog(self):
        options = QFileDialog.Options()
        self.TTS_rf_file_path, _ = QFileDialog.getOpenFileName(self, "选择参考音频", "", "参考音频 (*.mp3)", options=options)
        if self.TTS_rf_file_path:
            self.checkfilename.setText(self.TTS_rf_file_path.split('/')[-1])
            self.checkfilename.setStyleSheet("color: green")
        else:
            self.TTS_rf_file_path = None
    def InstallFileDialog(self):
        try:
            self.import_certificate_windows()
            self.appendConsole("证书导入成功！")
        except Exception as e:
            if self.is_admin():
                self.appendConsole("证书导入失败！请向开发者反馈")
                self.appendConsole(f"{e}")
                self.displayError("证书导入失败！")
            else:
                self.appendConsole("请使用管理员权限运行程序！")
                self.displayError("非管理员权限运行程序")
        temp_list = ['seleniumwire.crt','mitmproxy_cert.crt']
        for f in temp_list:
            try:
                os.remove(f)
            except:
                pass
    def import_certificate_windows(self):
        with open('seleniumwire.crt', 'w', encoding='utf-8') as f:
            f.write(cert())
        with open('mitmproxy_cert.crt', 'w', encoding='utf-8') as f:
            f.write(cert_mitmproxy())
        subprocess.check_call(['certutil', '-addstore', 'ROOT', 'seleniumwire.crt'])
        self.appendConsole("seleniumwire证书成功导入到受信任的根证书颁发机构存储区。")
        subprocess.check_call(['certutil', '-addstore', 'ROOT', 'mitmproxy_cert.crt'])
        self.appendConsole("mitmproxy证书成功导入到受信任的根证书颁发机构存储区。")
    def log_config(self,text):
        if self.log.isChecked():
            current_time = datetime.now().strftime("%H:%M:%S")
            with open(f"./config/{self.RunTime}.txt",'a',encoding='utf-8') as f:
                f.write(str(current_time)+"："+str(text)+'\n')
        else:
            pass
    def ShowHelp(self, text):
        QMessageBox.information(self, "帮助", text)
    def ShowT3Info(self):
        if self.T3_checkbox.isChecked():
            # 如果勾选了“秒杀模式”选项，弹出警告窗口
            QMessageBox.warning(self, "警告", "[ 秒杀模式开启 ] 勾选后不再等待听力播放，直接选择答案，请注意！")
        else:
            pass
    def ShowTalkInfo(self,state):
        if state == Qt.Checked and self.IS_TALK_checkbox.isChecked():
            # 如果勾选了“完成口语”选项，弹出警告窗口
            QMessageBox.warning(self, "警告", "[ 口语功能开启 ] 开启之前确保ADB已连接手机，并且手机已开启开发者选项，允许USB调试，并且手机已连接到电脑。")
        else:
            pass
    def toggleAutoLogin(self):
        if self.auto_login_checkbox.isChecked():
            self.username_label.show()
            self.username_input.show()
            self.password_label.show()
            self.password_input.show()
        else:
            self.username_label.hide()
            self.username_input.hide()
            self.password_label.hide()
            self.password_input.hide()

    def onStart(self):
        """启动任务线程"""
        self.RunTime = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
        Init_Info = f'''###################初始化信息#####################
[ 开始时间 ]：{self.RunTime}
[ 用户名 ]：{self.username_input.text()}
[ 密码 ]：{self.password_input.text()}
[ 秒杀模式 ]：{self.T3_checkbox.isChecked()}
[ 完成口语 ]：{self.IS_TALK_checkbox.isChecked()}
[ 最低分数 ]：{self.LOW_SCORE_combo.currentText()}
[ 隐式等待时间 ]：{self.implicitly_wait_time_combo.currentText()}
[ 模式 ]：{self.Unit_or_Level.currentText()}
[ 日志记录 ]：{self.log.isChecked()}
[ 错误答案 ]：{self.WRONG_ANSWER_combo.currentText()}
###################系统输出开始###################
        '''
        with open(f"./config/{self.RunTime}.txt",'w',encoding='utf-8') as f:
            f.write(Init_Info)
        self.start_button.setEnabled(False)
        self.console_output.append("程序已开始...")
        self.error_output.setText("错误信息：无")
        self.work_thread = ProgramThread(
            username=self.username_input.text(),
            password=self.password_input.text(),
            T3=self.T3_checkbox.isChecked(),
            H=self.H_checkbox.isChecked(),
            IS_TALK=self.IS_TALK_checkbox.isChecked(),
            LOW_SCORE=self.LOW_SCORE_combo.currentText(),
            WRONG_ANSWER=self.WRONG_ANSWER_combo.currentText(),
            implicitly_wait_time=self.implicitly_wait_time_combo.currentText(),
            Unit_or_Level=self.Unit_or_Level.currentText(),
            TTS=self.IS_TTS_checkbox.isChecked(),
            rf_audio=self.TTS_rf_file_path,
            rf_text=self.TTS_rf_text_line.text(),
            FastRead=self.FastRead_checkbox.isChecked()
        )
        self.work_thread.info.connect(self.appendConsole)
        self.work_thread.info.connect(self.log_config)
        self.work_thread.error_signal.connect(self.displayError)
        self.work_thread.finished.connect(lambda:self.start_button.setEnabled(True))
        self.work_thread.finished.connect(lambda:self.delayOnStop())
        self.work_thread.pause_signal.connect(self.showContinueButton)
        self.work_thread.updateBar.connect(self.update_progress)
        self.work_thread.thread_running.connect(self.thread_running)
        self.thread_timer = QTimer()
        self.thread_timer.timeout.connect(self.update_thread_loading)
        self.thread_animation_frames = ["|", "/", "—", "\\"]
        self.work_thread.start()
        self.stop_button.setEnabled(True)
    def update_thread_loading(self):
        self.thread_current_frame = (self.thread_current_frame + 1) % len(self.thread_animation_frames)
        self.thread_running_animation_label.setText(f'等待修改数据中 {self.thread_animation_frames[self.thread_current_frame]}')
    def thread_running(self,status):
        if status:
            self.thread_running_animation_label.show()
            self.thread_running_animation_label.setStyleSheet("color: #4f5d73")
            self.thread_current_frame = 0
            self.thread_timer.start(200)
        else:
            self.thread_running_animation_label.setText('数据修改成功！')
            self.thread_running_animation_label.setStyleSheet("color: green")
            QTimer.singleShot(2000, self.thread_running_animation_label.hide)
            self.thread_timer.stop()
    def thread_close_Event(self):
        try:
            self.work_thread.close_Event()
        except:
            pass
    def delayOnStop(self):
        """延迟停止任务线程"""
        self.thread_close_Event()
        QTimer.singleShot(2000, self.onStop)
    def kill_process_by_name(self,process_name):
        try:
            # 使用 taskkill 命令来终止进程
            subprocess.run(["taskkill", "/f", "/im", process_name], check=True)
            self.appendConsole(f"成功关闭进程: {process_name}")
        except subprocess.CalledProcessError as e:
            self.appendConsole(f"进程不存在或无权限: {process_name}")
    def kill_processes(self):
        try:
            self.appendConsole("正在清理缓存文件...")
            if os.path.exists('temp'):
                shutil.rmtree('temp')
                self.appendConsole("temp 文件夹已删除。")
            if os.path.exists('temp_info'):
                shutil.rmtree('temp_info')  
                self.appendConsole("temp_info 文件夹已删除。")
            if os.path.exists('sign.txt'):
                os.remove('sign.txt')
                self.appendConsole("sign.txt 文件已删除。")
        except:
            pass
        sys.stdout.reconfigure(encoding='utf-8')
        self.appendConsole("正在结束相关进程...")
        processes_to_kill = ['msedgedriver.exe', 'msedgewebview2.exe', 'adb.exe']
        if self.FastRead_checkbox.isChecked():
            try:
                self.kill_process_by_name('proxy.exe')
            except:
                pass
            set_system_proxy(enable=False) # 关闭代理
            self.appendConsole("代理已恢复。")
        for process in processes_to_kill:
            self.kill_process_by_name(process)
        try:
            for file in os.listdir('temp'):
                os.remove(f'temp/{file}')
        except:
            self.appendConsole("temp文件夹清除失败...")
        self.appendConsole("相关进程已结束,相关文件已清理。")
    def onStop(self):
        """停止任务线程"""
        self.thread_close_Event()
        if self.work_thread and self.work_thread.isRunning():
            try:
                if self.thread_timer.isActive():
                    self.thread_timer.stop()
                    self.thread_running_animation_label.hide()
                self.continue_button.hide()
                self.stop_button.setEnabled(False)
                self.progress_bar.setValue(0)
                self.progress_bar.hide()
                # 尝试终止线程
                self.work_thread.terminate()
                self.work_thread.wait()  # 等待线程终止
                self.kill_processes()  # 终止相关进程

                if not self.work_thread.isRunning():
                    self.appendConsole("程序已正常终止")
                else:
                    self.appendConsole("程序未正常终止，尝试强制停止")
                
                self.work_thread = None
                self.start_button.setEnabled(True)
            except Exception as e:
                self.appendConsole(f"程序未正常终止，请手动运行 clean.bat: {str(e)}")
                self.work_thread = None
                self.continue_button.hide()
                self.start_button.setEnabled(True)
                self.stop_button.setEnabled(False)
                self.progress_bar.setValue(0)
                self.progress_bar.hide()
        else:
            self.start_button.setEnabled(True)
            self.stop_button.setEnabled(False)
            self.progress_bar.setValue(0)
            self.progress_bar.hide()
            try:
                self.kill_processes()
            except Exception as e:
                pass
            self.appendConsole("程序未运行，无法停止")

    def onContinue(self):
        """恢复任务线程"""
        if self.work_thread:
            self.work_thread.continue_execution()
            self.continue_button.hide()
        else:
            self.appendConsole("程序未运行，无法继续")
    def appendConsole(self, message):
        current_time = datetime.now().strftime("%H:%M:%S")
        self.console_output.append(str(current_time)+"："+message)
    def displayError(self, error_message):
        self.error_output.setText(f"错误信息：{error_message}")
        self.error_output.setStyleSheet("color: red;")
    def showContinueButton(self):
        """显示继续按钮"""
        self.continue_button.show()

    def loadConfig(self):
        """加载配置文件"""

        self.IS_TALK_checkbox.stateChanged.disconnect(self.ShowTalkInfo)
        self.T3_checkbox.stateChanged.disconnect(self.ShowT3Info)
        config_folder = './config'
        if not os.path.exists(config_folder):
            os.makedirs(config_folder)
        config_file = os.path.join(config_folder, 'config.json')
        if os.path.exists(config_file):
            with open(config_file, 'r',encoding='utf-8') as f:
                config_data = json.load(f)
                self.auto_login_checkbox.setChecked(config_data.get('auto_login', False))
                self.username_input.setText(config_data.get('username', ''))
                self.password_input.setText(config_data.get('password', ''))
                self.T3_checkbox.setChecked(config_data.get('T3', False))
                self.H_checkbox.setChecked(config_data.get('H', False))
                self.IS_TALK_checkbox.setChecked(config_data.get('IS_TALK', False))
                self.IS_TTS_checkbox.setChecked(config_data.get('IS_TTS', False))
                self.LOW_SCORE_combo.setCurrentText(config_data.get('LOW_SCORE', '60'))
                self.WRONG_ANSWER_combo.setCurrentText(config_data.get('WRONG_ANSWER', '1'))
                self.implicitly_wait_time_combo.setCurrentText(config_data.get('implicitly_wait_time', '10'))
                self.Unit_or_Level.setCurrentText(config_data.get('Unit_or_Level', 'Unit'))
                self.TTS_rf_file_path = config_data.get('rf_audio', "")
                self.TTS_rf_text_line.setText(config_data.get('rf_text', ''))
                self.FastRead_checkbox.setChecked(config_data.get('FastRead', False))
        if self.TTS_rf_file_path != None and self.TTS_rf_file_path != "" and not os.path.exists(self.TTS_rf_file_path):
            self.checkfilename.setText("上次选择的文件不存在！")
            self.checkfilename.setStyleSheet("color: red")
            self.TTS_rf_text_line.setText("")
        elif self.TTS_rf_file_path != None and self.TTS_rf_file_path != "":
            self.checkfilename.setText(self.TTS_rf_file_path.split('/')[-1])
            self.checkfilename.setStyleSheet("color: green")
        else:
            self.checkfilename.setText("未选择")
        if not self.IS_TALK_checkbox.isChecked():
            self.checkfilename.hide()
            self.TTS_rf_text_label.hide()
            self.TTS_rf_text_line.hide()
            self.TTS_path_filed_button.hide()
        self.IS_TALK_checkbox.stateChanged.connect(self.ShowTalkInfo)
        self.T3_checkbox.stateChanged.connect(self.ShowT3Info)
    def saveConfig(self):
        """保存配置文件"""
        if self.log.isChecked():
            config_folder = './config'
            if not os.path.exists(config_folder):
                os.makedirs(config_folder)
            config_data = {
                'auto_login': self.auto_login_checkbox.isChecked(),
                'username': self.username_input.text(),
                'password': self.password_input.text(),
                'T3': self.T3_checkbox.isChecked(),
                'H': self.H_checkbox.isChecked(),
                'IS_TALK': self.IS_TALK_checkbox.isChecked(),
                'IS_TTS': self.IS_TTS_checkbox.isChecked(),
                'LOW_SCORE': self.LOW_SCORE_combo.currentText(),
                'WRONG_ANSWER': self.WRONG_ANSWER_combo.currentText(),
                'implicitly_wait_time': self.implicitly_wait_time_combo.currentText(),
                'Unit_or_Level': self.Unit_or_Level.currentText(),
                'rf_audio':self.TTS_rf_file_path if self.TTS_rf_file_path != None else "",
                'rf_text':self.TTS_rf_text_line.text(),
                'FastRead':self.FastRead_checkbox.isChecked()
            }
            config_file = os.path.join(config_folder, 'config.json')
            with open(config_file, 'w',encoding='utf-8') as f:
                json.dump(config_data, f, indent=4,ensure_ascii=False)
            QMessageBox.information(self, "提示", "配置已保存!")
    def closeEvent(self, event):
        try:
            self.onStop()
        except:
            pass
        self.saveConfig()
        event.accept()
